import {app, BrowserWindow, dialog, ipcMain, protocol, shell} from 'electron'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'
import * as path from "path";
import FileUtil from "@/utils/FileUtil";
import OpenDialogSyncOptions = Electron.OpenDialogSyncOptions;
import Downloader from "@/utils/Downloader";

protocol.registerSchemesAsPrivileged([
    {scheme: 'app', privileges: {secure: true, standard: true}}
])

const isDevelopment = process.env.NODE_ENV !== 'production'

function createWindow() {
    const win = new BrowserWindow({
        width: 1280,
        height: 800,
        minWidth: 1280,
        minHeight: 800,
        title: 'Envor',
        webPreferences: {
            nodeIntegration: (process.env
                .ELECTRON_NODE_INTEGRATION as unknown) as boolean,
            contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
            webSecurity: false,
            preload: path.join(__dirname, 'preload.js')
        }
    })

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
        win.loadURL('app://./index.html')
    }

    // 窗体控制
    // 关闭窗体
    ipcMain.on('close-app', (event) => {
        win.close()
    })

    // 最大化窗体
    ipcMain.on('max-app', (event) => {
        win.maximize()
    })

    // 还原窗体
    ipcMain.on('unmax-app', (event) => {
        win.unmaximize()
    })

    // 最小化窗体
    ipcMain.on('min-app', (event) => {
        win.minimize()
    })

    win.on('maximize', () => {
        win.webContents.send('max-handle', true)
    })

    win.on('unmaximize', () => {
        win.webContents.send('max-handle', false)
    })

    ipcMain.on('openBrowser', (event: any, url: string) => {
        // 打开系统默认浏览器到指定的url
        shell.openExternal(url)
    })

    ipcMain.handle('openDialog', (e, options: OpenDialogSyncOptions) => {
        return dialog.showOpenDialogSync(options);
    })

    ipcMain.on('download', (event, url, filename) => {
        const downloader = Downloader.build();
        downloader.openPart(10).setOutPath(filename).exe(url, Downloader.getName(url));
        return;
        FileUtil.download({
            url,
            path: filename,
            error: () => {
                event.reply('onReleaseDownloadError');
            },
            progress: (progress) => {
                event.reply('onReleaseDownload', progress);
            },
            success: () => {
                event.reply('onReleaseDownloadSuccess');
            }
        });
    })

    ipcMain.handle('unzip', (e, path, outPath) => {
        return FileUtil.unzip(path, 'D:\\developers\\environments\\test');
    })

}

// 当所有窗口被关闭的时候退出程序
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    // if (isDevelopment && !process.env.IS_TEST) {
    //   // Install Vue Devtools
    //   try {
    //     await installExtension(VUEJS3_DEVTOOLS)
    //   } catch (e) {
    //     console.error('Vue Devtools failed to install:', e.toString())
    //   }
    // }
    createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}
